import random
import time

import requests

from common.dbutils import DBUtils
from config import URLPATH


class Register:

    #  使用session保持会话状态
    def __init__(self):
        self.session = requests.session()

    # 获取图⽚验证码
    def get_imgverify(self,r):
        return self.session.get(url=f"{URLPATH}/common/public/verifycode1/{r}")

    # 获取短信验证码
    def get_smsverify(self, phone,imgVerifyCode,type='reg'):
        return self.session.post(url=f"{URLPATH}/member/public/sendSms",
                      headers={"Content-Type": "application/x-www-form-urlencoded"},
                      data={"phone": phone, "imgVerifyCode": imgVerifyCode, "type": type})

    # 注册
    def reg_data(self, phone, password, verifycode,phone_code,dy_server='on',invite_phone=None):
        return self.session.post(url=f"{URLPATH}/member/public/reg",
                      headers={"Content-Type": "application/x-www-form-urlencoded"},
                      data={"phone": phone, "password": password, "verifycode": verifycode, "phone_code": phone_code, "dy_server": dy_server, "invite_phone": invite_phone})



if __name__ == '__main__':
    r = Register()
    # 随机小数
    ranNum = random.uniform(0, 1)
    # 随机字符串
    ranString = '123456789a'
    # cookie = None
    print(r.get_imgverify(ranNum).headers)

    # 处理手机号唯一性问题-数据库操作
    phone = 18888888888
    password = '123456'
    imgcode = 8888
    phone_code = 666666
    db = DBUtils()
    db.execute_sql(f"delete from mb_member where phone={phone};")
    db.execute_sql(f"delete from mb_member_info where member_name='{phone}';")
    db.execute_sql(f"delete from mb_member_login_log where member_name='{phone}';")
    db.execute_sql(f"delete from mb_member_register_log where phone={phone};")

    number = r.get_smsverify(phone, imgcode).json()
    print(r.get_smsverify(phone, imgcode).headers)
    print(number)
    # time.sleep(60)
    regis = r.reg_data(phone, password, imgcode, phone_code).json()
    print(r.reg_data(phone, password, imgcode, phone_code).headers)
    print(regis)

